<template>
  <div>
    <h1>答题界面</h1>

    <el-form>
      <div
        v-for="question in displayedQuestions"
        :key="question.questionId"
        class="question-container"
      >
        <el-card class="question-card">
          <p><strong>题目：</strong>{{ question.questionContent }}</p>

          <!-- 单选题 -->
          <div v-if="question.questionType === 1" class="single-choice">
            <el-radio-group
              v-model="userAnswers[question.questionId]"
              @change="checkAnswer(question.questionId)"
              :disabled="isAnswered(question.questionId)"
            >
              <el-radio
                v-for="option in question.answer"
                :key="option.id"
                :value="option.id"
              >
                {{ option.answer }}
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 多选题 -->
          <div v-if="question.questionType === 2" class="multiple-choice">
            <el-checkbox-group
              v-model="userAnswers[question.questionId]"
              @change="checkAnswer(question.questionId)"
              :disabled="isAnswered(question.questionId)"
            >
              <el-checkbox
                v-for="option in question.answer"
                :key="option.id"
                :value="option.id"
              >
                {{ option.answer }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 判断题 -->
          <div v-if="question.questionType === 3" class="true-false">
            <el-radio-group
              v-model="userAnswers[question.questionId]"
              @change="checkAnswer(question.questionId)"
              :disabled="isAnswered(question.questionId)"
            >
              <el-radio :value="true">正确</el-radio>
              <el-radio :value="false">错误</el-radio>
            </el-radio-group>
          </div>

          <!-- 简答题 -->
          <div v-if="question.questionType === 4" class="short-answer">
            <el-input
              type="textarea"
              v-model="userAnswers[question.questionId]"
              @blur="checkAnswer(question.questionId)"
              :disabled="isAnswered(question.questionId)"
            />
          </div>

          <!-- 结果反馈 -->
          <p v-if="feedback[question.questionId] !== undefined">
            <strong>结果：</strong>
            <span :class="{ correct: feedback[question.questionId] === true }"
              >正确</span
            >
            <span v-if="feedback[question.questionId] === false">错误</span>
          </p>
        </el-card>
      </div>
    </el-form>

    <div class="result-summary">
      <p><strong>正确数量：</strong>{{ start.rigth }}</p>
      <p><strong>错误数量：</strong>{{ start.wrong }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { getQuestionsByBankId } from '@/api/ExamOnline/Train'

const route = useRoute()
const bankId = route.params.bankId as string
const additionalParameter = Number(route.params.additionalParameter)
const questions = ref<any[]>([])
const userAnswers = ref<Record<number, any>>({})
const feedback = ref<Record<number, boolean | undefined>>({})

// 定义 correctCount 和 wrongCount
const start = reactive({
  rigth: 0,
  wrong:0,
  correctCount: 0,
  wrongCount: 0
})



const displayedQuestions = computed(() => {
  let filteredQuestions = [...questions.value]

  // 根据 additionalParameter 进行筛选和排序
  switch (additionalParameter) {
    case 1:
      // 显示所有问题
      console.log('Showing all questions')
      break
    case 2:
      // 随机排序
      filteredQuestions = filteredQuestions.sort(() => Math.random() - 0.5)
      console.log('Questions after random sorting:', filteredQuestions)
      break
    case 3:
      // 筛选单选题
      filteredQuestions = filteredQuestions.filter((q) => q.questionType === 1)
      console.log('Single choice questions:', filteredQuestions)
      break
    case 4:
      // 筛选多选题
      filteredQuestions = filteredQuestions.filter((q) => q.questionType === 2)
      console.log('Multiple choice questions:', filteredQuestions)
      break
    case 5:
      // 筛选判断题
      filteredQuestions = filteredQuestions.filter((q) => q.questionType === 3)
      console.log('True/False questions:', filteredQuestions)
      break
    default:
      console.warn('Unknown additionalParameter value:', additionalParameter)
  }

  return filteredQuestions
})

async function fetchQuestions(bankId: string) {
  try {
    const response = await getQuestionsByBankId(bankId)
    console.log(response.data.data)

    if (response.data.code === 200) {
      questions.value = response.data.data
      // 确保在数据更新后触发视图更新
      await nextTick()
    } else {
      console.error(
        'Error fetching questions:',
        response.data.message || 'Unknown error'
      )
    }
  } catch (error) {
    console.error('Failed to fetch questions:', error.message || error)
  }
}

function checkAnswer(questionId: number) {
  const question = questions.value.find((q) => q.questionId === questionId)
  if (!question) return

  const userAnswer = userAnswers.value[questionId]
  const correctAnswers = question.answer
    .filter((a: any) => a.isTrue === 'true')
    .map((a: any) => a.id)

  let isCorrect = false
  if (question.questionType === 1) {
    // 单选题
    isCorrect = correctAnswers.includes(userAnswer)
  } else if (question.questionType === 2) {
    // 多选题
    isCorrect =
      correctAnswers.every((a: number) => userAnswer.includes(a)) &&
      userAnswer.every((a: number) => correctAnswers.includes(a))
  } else if (question.questionType === 3) {
    // 判断题
    isCorrect = correctAnswers[0] === userAnswer
  } else if (question.questionType === 4) {
    // 简答题
    isCorrect = userAnswer.trim() !== ''
  }

  // 更新反馈数据并触发响应式变化
  feedback.value = { ...feedback.value, [questionId]: isCorrect }
  console.log('Updated feedback:', feedback.value)
}

// 使用 watch 监听 feedback 的变化
watch(() => feedback.value, (newFeedback) => {
  console.log('Feedback changed:', newFeedback)
  start.correctCount = Object.values(newFeedback).filter((value) => value === true).length
  start.wrongCount = Object.values(newFeedback).filter((value) => value === false).length
  console.log('Correct count:', start.correctCount)
  start.rigth = start.correctCount
  console.log('Wrong count:', start.wrongCount)
  start.wrong = start.wrongCount
}, { deep: true })

function isAnswered(questionId: number) {
  return feedback.value[questionId] !== undefined
}

onMounted(async () => {
  console.log('additionalParameter:', additionalParameter)

  if (bankId) {
    await fetchQuestions(bankId)
  } else {
    console.error('Bank ID is not defined.')
  }
})
</script>

<style scoped>
.question-container {
  margin-bottom: 20px;
}

.question-card {
  margin-bottom: 10px;
}

.result-summary {
  margin-top: 20px;
}

.correct {
  color: green;
}

span {
  margin-right: 10px;
}
</style>